<script setup lang="ts">
import { useNewLotteryStore } from '@/stores/newlottery'
import IconMinusOutlined from './icons/IconMinusOutlined.vue'
import IconPlusOutlined from './icons/IconPlusOutlined.vue'
import { onMounted } from 'vue'
import { useToast } from 'vue-toastification'

const newLotteryStore = useNewLotteryStore()

type TLotteryNumberProps = {
  enableSwitchMethod?: boolean
}

defineProps<TLotteryNumberProps>()

const emit = defineEmits<{
  (e: 'startDraw'): void
  (e: 'endDraw'): void
}>()

// 获取默认抽奖次数
const getDefaultDrawCount = (remainingCount: number) => {
  if (remainingCount <= 0) return 0
  if (remainingCount <= 10) return remainingCount
  return 10
}

// 初始化默认抽奖次数
onMounted(() => {
  const currentPrize = newLotteryStore.lottery.getCurrentPrize()
  const remainingCount = currentPrize?.getStock() || 0
  if (currentPrize?.getNumberOfDraws() === 0) {
    currentPrize.setNumberOfDraws(getDefaultDrawCount(remainingCount))
  }
})

// 增加抽奖人数
const handleIncrement = () => {
  if (!newLotteryStore.allowMultipleDraws) return

  const currentPrize = newLotteryStore.lottery.getCurrentPrize()
  const remainingCount = currentPrize.getStock()
  const currentDraws = currentPrize.getNumberOfDraws()

  if (currentDraws < remainingCount) {
    currentPrize.setNumberOfDraws(currentDraws + 1)
  }
}

// 减少抽奖人数
const handleDecrement = () => {
  if (!newLotteryStore.allowMultipleDraws) return

  const currentPrize = newLotteryStore.lottery.getCurrentPrize()
  const currentDraws = currentPrize.getNumberOfDraws()

  if (currentDraws > 1) {
    currentPrize.setNumberOfDraws(currentDraws - 1)
  }
}

const toast = useToast()

// 开始抽奖
const handleStartDraw = async () => {
  if (newLotteryStore.lottery.getCurrentPrize()?.getStock() === 0) {
    toast.error('当前奖品剩余抽奖人数为0')
    return
  } // 如果没有剩余抽奖人数，则不允许抽奖
  const flag = newLotteryStore.startDrawing()
  if (flag) {
    emit('startDraw') // 触发开始抽奖事件
    emit('endDraw') // 触发结束抽奖事件
  }
}
</script>

<template>
  <div class="flex flex-col justify-center select-none">
    <div class="px-4 flex justify-center items-center bg-black/45 text-white">
      <span class="text-xs">一次抽取</span>
      <button class="w-10 h-10 mx-2" @click.stop="handleDecrement">
        <IconMinusOutlined />
      </button>
      <span>{{ newLotteryStore.lottery.getCurrentPrize()?.getNumberOfDraws() || 0 }}</span>
      <button class="w-10 h-10 mx-2" @click.stop="handleIncrement">
        <IconPlusOutlined />
      </button>
      <span class="text-xs">人</span>
      <span class="text-xs ml-2">
        ( 剩余{{ newLotteryStore.lottery.getCurrentPrize()?.getStock() || 0 }}人 )
      </span>
    </div>
    <div class="flex justify-center mt-4">
      <button
        class="px-4 py-1 rounded bg-yellow-600 hover:bg-yellow-400 active:bg-yellow-600"
        @click.stop="handleStartDraw"
      >
        <span class="font-semibold text-sm text-red-800"> 开始抽奖 </span>
      </button>
    </div>
  </div>
</template>
